package com.suanfa.node;

import java.util.Stack;

/**
 * 通过单链表模拟加法
 */
public class NodePlus {

    public static void main(String[] args) {
      String s1 = "752";
      String s2 = "853";
      Node n1 = parse(s1);
      Node n2 = parse(s2);
      Node result = plus(n1, n2);
      Node n = result;
      Stack stack = new Stack();
      while(n != null){
          System.out.print(n.val + ",");
          stack.push(n.val);
          n = n.next;
      }
        System.out.println();
      int size = stack.size();
      for(int i=0; i<size; i++){
          System.out.print(stack.pop());
      }
    }

    public static Node parse(String s1){
        Node n1 = null;
        Node cur = null;
        char[]c = s1.toCharArray();
        for(int i = c.length-1; i >= 0; i--){
            Node node = new Node(Integer.valueOf(String.valueOf(c[i])));
            if(n1 == null){
              n1 = node;
              cur = n1;
            } else {
              cur.next = node;
              cur = cur.next;
            }
        }
        return n1;
    }

    public static Node plus(Node n1, Node n2){
        Node node = new Node(-1);
        Node current = node;
        Node l1 = n1;
        Node l2 = n2;
        Integer num = 0;
        while(l1 != null || l2 != null){
            Integer num1 = l1 == null? 0: l1.val;
            Integer num2 = l2== null? 0: l2.val;
            int total = num1 + num2 + num;

            //1、 total<10 total=10 total > 10
            int val = total>=10? total - 10 : total;
            if(current.val == -1){
                current.val = val;
            }else {
                Node newNode = new Node(val);
                current.next = newNode;
                current = current.next;
            }
            num = total/10;
            l1 = l1 == null? null: l1.next;
            l2 = l2 == null? null: l2.next;
        }
        if(num > 0){
            Node newNode = new Node(num);
            current.next = newNode;
        }

        return  node;
    }

}

class Node{
    public Node next;

    public Integer val;

    public Node(Integer val) {
        this.val = val;
    }
}
